import { checkAuthApi } from '../services';

import * as actionType from './actionType';

export const loginSuccess = ()=> {
  return {
    type: actionType.LOGIN_SUCCESS
  }
}

export const loginFailed = ()=> {
  return {
    type: actionType.LOGIN_FAILED
  }
}

export const checkAuth = ()=> {
  const token = window.localStorage.getItem("cors-token");

  //此处是异步action，手动dispatch
  return (dispatch) => {
    if(!token) {
      dispatch(loginFailed());
      dispatch({
        type: actionType.CHECK_AUTH_COMPLETED
      })
    } else {
      //验证token
      checkAuthApi(token)
        .then(resp => {
          if(resp.data.code === 200 && resp.data.data.status === "OK") {
            dispatch(loginSuccess())
          } else {
            dispatch(loginFailed())
          }
        }).catch(err => {
          dispatch(loginFailed())
        }).finally(()=> {
          dispatch({
            type: actionType.CHECK_AUTH_COMPLETED
          })
        })
    }
  }
}